<template>
  <div class="page-container">
    <!--表格内容栏-->
    <ac-table
      ref="dataTable"
      pkName="id"
      :filters="filters"
      :filterFields="filterFields"
      :columns="columns"
      @handleTableOperator="handleTableOperator"
      @handleCellOperator="handleCellOperator"
    />

    <!--新增/编辑/查看界面-->
    <el-dialog
      width="650px"
      v-model="dialogVisible"
      :title="dialogTitle"
      :close-on-click-modal="false"
      destroy-on-close
      draggable
    >
      <el-form
        :model="formData"
        ref="dataForm"
        label-width="120px"
        label-position="right"
        :disabled="!dialogEdit"
        :rules="rules" 
        :hide-required-asterisk="!dialogEdit"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据库类型" prop="databaseId">
              <ac-remote-select
                v-model="formData.databaseId"
                dataUrl="/system/database/queryPage"
                :option="{id: formData.databaseId, name: formData.databaseName}"
                @change="changeDatabase"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据源编码" prop="code">
              <el-input v-model="formData.code" :disabled="true" placeholder="系统自动生成" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据源名称" prop="name">
              <el-input v-model="formData.name"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="驱动类名" prop="dbDriver">
              <el-input v-model="formData.dbDriver"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据库地址" prop="dbIp">
              <el-input v-model="formData.dbIp"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据库端口" prop="dbPort">
              <ac-number v-model="formData.dbPort" :point="0"></ac-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="数据库名" prop="dbName">
              <el-input v-model="formData.dbName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formData.ifSchema === '1'">
          <el-col :span="24">
            <el-form-item label="模式名" prop="dbSchema">
              <el-input v-model="formData.dbSchema" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="账号" prop="dbUsername">
              <el-input v-model="formData.dbUsername"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="密码" prop="dbPassword">
              <el-input v-model="formData.dbPassword" type="password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!dialogEdit">
          <el-col :span="24">
            <el-form-item label="连接地址" prop="dbUrl">
              <el-input v-model="formData.dbUrl"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!dialogEdit">
          <el-col :span="24">
            <el-form-item label="更新时间" prop="updateTime">
              <ac-datetime v-model="formData.updateTime" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!dialogEdit">
          <el-col :span="24">
            <el-form-item label="创建时间" prop="createTime">
              <ac-datetime v-model="formData.createTime" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button 
          v-if="dialogEdit"
          size="default"
          type="info"
          @click="dialogVisible=false"
        >取消</el-button>
        <el-button
          v-if="dialogEdit"
          size="default"
          type="success"
          @click="connectForm"
          :loading="editLoading"
        >连接测试</el-button>
        <el-button 
          v-if="dialogEdit"
          size="default"
          type="primary"
          @click="submitForm"
          :loading="editLoading"
        >提交</el-button>
        <el-button 
          v-if="!dialogEdit"
          size="default"
          type="info"
          @click="dialogVisible=false"
        >关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import api from '@/http/api';

const filters = ref({
  name: ''
});

const filterFields = ref([
  {prop: "name", label: "名称"}
]);

const columns = ref([
  {prop: "name", label: "数据源名称", width: 250, click: true},
  {prop: "code", label: "数据源编码", width: 170},
  {prop: "databaseName", label: "数据库类型", width: 110},
  {prop: "dbIp", label: "数据库地址", width: 160},
  {prop: "dbPort", label: "数据库端口", width: 120, type: 'number', point: 0},
  {prop: "dbName", label: "数据库名", width: 130},
  {prop: "dbUrl", label: "连接地址", minWidth: 120},
  {prop: "updateTime", label: "更新时间", width: 160, type: "datetime"},
]);

const rules = ref({
  databaseId: [
    {required: true, message: '请选择数据库类型', trigger: 'change'},
    {max: 20, message: '长度必须小于等于 20 个字符！', trigger: 'change'}
  ],
  name: [
    {required: true, message: '请输入数据源名称', trigger: 'change'},
    {max: 100, message: '长度必须小于等于 100 个字符！', trigger: 'change'}
  ],
  dbIp: [
    {required: true, message: '请输入数据库地址', trigger: 'change'},
    {max: 50, message: '长度必须小于等于 50 个字符！', trigger: 'change'}
  ],
  dbPort: [
    {required: true, message: '请输入数据库端口', trigger: 'change'},
  ],
  dbName: [
    {required: true, message: '请输入数据库名', trigger: 'change'},
    {max: 50, message: '长度必须小于等于 100 个字符！', trigger: 'change'}
  ],
  dbSchema: [
    {required: true, message: '请输入模式名', trigger: 'change'},
    {max: 50, message: '长度必须小于等于 100 个字符！', trigger: 'change'}
  ],
  dbUsername: [
    {required: true, message: '请输入用户名', trigger: 'change'},
    {max: 50, message: '长度必须小于等于 50 个字符！', trigger: 'change'}
  ],
  dbPassword: [
    {required: true, message: '请输入密码', trigger: 'change'},
    {max: 50, message: '长度必须小于等于 50 个字符！', trigger: 'change'}
  ],
  dbDriver: [
    {required: true, message: '请输入驱动类名', trigger: 'change'},
    {max: 100, message: '长度必须小于等于 100 个字符！', trigger: 'change'}
  ],
});

const dataTable = ref();
const dataForm = ref();
const formData = ref({});
const dialogTitle = ref('');
const dialogVisible = ref(false);
const editLoading = ref(false);
const dialogEdit = ref(false);

const handleCellOperator = (property, value, row) => {
  formData.value = Object.assign({}, row);
  dialogVisible.value = true;
  dialogEdit.value = false;
  dialogTitle.value = "查看";

  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const handleTableOperator = (button, row) => {
  dialogVisible.value = true;
  dialogEdit.value = true;
  dialogTitle.value = "编辑";

  if (button.buttonType === 'edit') {
    formData.value = Object.assign({}, row, {button: button});
  } else {
    formData.value = {button: button};
  }

  nextTick(() => {
    dataForm.value && dataForm.value.clearValidate();
  });
};

const changeDatabase = () => {
  if (formData.value.databaseId) {
    api.post('/system/database/queryBy', {id: formData.value.databaseId}).then(res => {
      if (res.data) {
        formData.value.dbDriver = res.data.driver || '';
        formData.value.dbPort = res.data.port || '';
        formData.value.ifSchema = res.data.ifSchema || '';
        nextTick(() => {
          dataForm.value && dataForm.value.clearValidate();
        });
      }
    });
  }
};

const connectForm = () => {
  dataForm.value && dataForm.value.validate((valid) => {
    if (valid) {
      editLoading.value = true;
      api.post('/system/datasource/connectTest', formData.value).then(res => {
        ElMessage.success(res.message);
        editLoading.value = false;
      }).catch(() => {
        editLoading.value = false;
      });
    } else {
      ElMessage.error('数据录入不正确，请重新检查！');
    }
  });
};

const submitForm = () => {
  dataForm.value && dataForm.value.validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('请确认是否提交？', '提示', {type: 'info'}).then(() => {
        editLoading.value = true;
        api.post(formData.value.button.dataDestUrl, formData.value).then(res => {
          ElMessage.success(res.message);
          dialogVisible.value = false;
          dataTable.value.findPage();
          editLoading.value = false;
        }).catch(() => {
          editLoading.value = false;
        });
      }).catch(() => {});
    } else {
      ElMessage.error('数据录入不正确，请重新检查！');
    }
  });
};
</script>